package cn.tedu.csmall.product.web;

import cn.tedu.csmall.product.ex.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
public class JsonResult<T> implements Serializable {
    /**
     * 操作结果状态码
     */
    @ApiModelProperty("业务状态码")
    private Integer state;
    /**
     * 操作“失败”时响应的提示文本
     */
    @ApiModelProperty("消息")
    private String message;
    /**
     * 操作正确响应的数据
     */
    @ApiModelProperty("数据")
    private T data;

    public static JsonResult ok() {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(ServiceCode.OK.getValue());
        return jsonResult;
    }
    public static<T> JsonResult<T> ok(T data) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(ServiceCode.OK.getValue());
        jsonResult.setData(data);
        return jsonResult;
    }

    public static JsonResult fail(ServiceException e) {
        return fail(e.getServiceCode(), e.getMessage());
    }

    public static JsonResult fail(ServiceCode state, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(state.getValue());
        jsonResult.setMessage(message);
        return jsonResult;
    }
}
